package cn.yuanqiao.web.controller.archive.formManage;

import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.archive.formManage.detail.domain.YqformManageDetail;
import cn.yuanqiao.archive.formManage.detail.service.IYqformManageDetailService;
import cn.yuanqiao.archive.storeRoom.service.InitializationService;

import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.domain.YqTable;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;

import cn.yuanqiao.archive.formManage.domain.YqformManage;
import cn.yuanqiao.archive.formManage.service.IYqformManageService;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.poi.ExcelUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

/**
 * 表单管理Controller
 * 
 * @author lyk
 * @date 2023-06-21
 */
@RestController
@RequestMapping("/archive/formManage")
public class YqformManageController extends BaseController
{
    @Autowired
    private IYqformManageService yqformManageService;

    @Autowired
    private InitializationService initializationService;

    @Autowired
    private IYqformManageDetailService yqformManageDetailService;


    /**
     * 查询表单管理列表
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:list')")
    @GetMapping("/list")
    public TableDataInfo list(YqformManage yqformManage)
    {
        yqformManage.setTenantCode(SecurityUtils.getTenantCode());
        startPage();
        List<YqformManage> list = yqformManageService.selectYqformManageList(yqformManage);
        return getDataTable(list);
    }

    @GetMapping("/list/one")
    public TableDataInfo listOne(YqformManage yqformManage)
    {
        yqformManage.setTenantCode(SecurityUtils.getTenantCode());
        List<YqformManage> list = yqformManageService.selectYqformManageListOne(yqformManage);
        return getDataTable(list);
    }

    /**
     * 查询表单管理列表
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:sync')")
    @PostMapping("/sync")
    public AjaxResult sync(YqformManage yqformManage)
    {
        //startPage();
        //List<YqformManage> list = yqformManageService.(yqformManage);
        List<YqTable> tableList = initializationService.getTableList();
        Iterator<YqTable> iterator = tableList.iterator();
        while (iterator.hasNext()) {
            YqTable item = iterator.next();
            List<YqformManageDetail> yqformManageDetails = yqformManageDetailService.selectTableColumnsByTableName(new YqformManageDetail().setTableName(SecurityUtils.getTenantCode()+"_"+item.getTableName()));
            Long tableId = item.getTableId();
            item.setTableId(SnowflakeIdGenerator.generateId());
            item.setTemplateId(tableId);
            if (yqformManageDetails.size() == 0 ){
                iterator.remove();
                continue;
            }
            YqformManage query = new YqformManage();
            query.setFormName(item.getTableName());
            query.setTenantCode(SecurityUtils.getTenantCode());
            List<YqformManage> yqformManages = yqformManageService.selectYqformManageList(query);

            if (yqformManages.size()!=0){
                boolean flag = false;
                for (YqformManage formItem : yqformManages) {
                    if ((formItem.getFormCode()==null||formItem.getFormCode().isEmpty())&&formItem.getIsEnable().equals("0")){
                        //未启用的代码直接删除
                        yqformManageDetails.forEach(detail->{
                            detail.setManageId(item.getTableId());
                            detail.setDetailId(SnowflakeIdGenerator.generateId());
                            detail.setTenantCode(SecurityUtils.getTenantCode());
                        });
                        yqformManageService.deleteYqformManageByFromId(String.valueOf(formItem.getFormId()), SecurityUtils.getTenantCode());
                        yqformManageDetailService.deleteYqformManageDetailByManageId(formItem.getFormId(),SecurityUtils.getTenantCode());
                        yqformManageDetailService.batchInsertYqformManageDetail(yqformManageDetails);
                    }else {
                        //已启用或已经设置，修改即可
                        yqformManageDetails.forEach(detail->{
                            detail.setManageId(formItem.getFormId());
                            detail.setDetailId(SnowflakeIdGenerator.generateId());
                            detail.setTenantCode(SecurityUtils.getTenantCode());
                        });
                        yqformManageDetailService.deleteYqformManageDetailByManageId(formItem.getFormId(),SecurityUtils.getTenantCode());
                        yqformManageDetailService.batchInsertYqformManageDetail(yqformManageDetails);
                        flag = true;
                    }
                }
                if (flag){
                    iterator.remove();
                }
            }
        }
        int i = addList(tableList);
        return AjaxResult.success(i);
    }

    private int addList(List<YqTable> yqTables){
        int i = yqformManageService.addList(yqTables,SecurityUtils.getTenantCode());
        return i;
    }

    /**
     * 导出表单管理列表
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:export')")
    @Log(title = "表单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YqformManage yqformManage)
    {
        yqformManage.setTenantCode(SecurityUtils.getTenantCode());
        List<YqformManage> list = yqformManageService.selectYqformManageList(yqformManage);
        ExcelUtil<YqformManage> util = new ExcelUtil<YqformManage>(YqformManage.class);
        util.exportExcel(response, list, "表单管理数据");
    }

    /**
     * 获取表单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:query')")
    @GetMapping(value = "/{fromId}")
    public AjaxResult getInfo(@PathVariable("fromId") String fromId)
    {
        return success(yqformManageService.selectYqformManageByFromId(fromId,SecurityUtils.getTenantCode()));
    }

    /**
     * 新增表单管理
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:add')")
    @Log(title = "表单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YqformManage yqformManage)
    {
        yqformManage.setTenantCode(SecurityUtils.getTenantCode());
        yqformManage.setFormId(SnowflakeIdGenerator.generateId());
        return toAjax(yqformManageService.insertYqformManage(yqformManage));
    }



    /**
     * 修改表单管理
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:edit')")
    @Log(title = "表单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YqformManage yqformManage)
    {
        yqformManage.setTenantCode(SecurityUtils.getTenantCode());
        return toAjax(yqformManageService.updateYqformManage(yqformManage));
    }

    /**
     * 删除表单管理
     */
    @PreAuthorize("@ss.hasPermi('archive:formManage:remove')")
    @Log(title = "表单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fromIds}")
    public AjaxResult remove(@PathVariable String[] fromIds)
    {
        return toAjax(yqformManageService.deleteYqformManageByFromIds(fromIds,SecurityUtils.getTenantCode()));
    }
}
